<template>
  <a-modal
    v-model:open="visible"
    title="编辑学员"
    ok-text="确认"
    cancel-text="取消"
    centered
    :width="484"
    :maskClosable="false"
    :confirmLoading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div v-if="init" class="float-left text-center mt-30">
      <a-spin />
    </div>

    <div v-else class="float-left mt-24">
      <a-form
        ref="formRef"
        :model="formState"
        :label-col="{ span: 7 }"
        :wrapper-col="{ span: 17 }"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <a-form-item
          label="学员头像"
          name="avatar"
          :rules="[{ required: true, message: '请上传学员头像!' }]"
        >
          <div class="d-flex">
            <img v-if="avatar" class="form-avatar mr-16" :src="avatar" alt="" />
            <UploadImageButton
              text="更换头像"
              @selected="onAvatarSelected"
            />
          </div>
        </a-form-item>

        <a-form-item
          label="学员姓名"
          name="name"
          :rules="[{ required: true, message: '请输入学员姓名!' }]"
        >
          <a-input
            v-model:value="formState.name"
            allow-clear
            style="width: 274px"
            placeholder="请填写学员姓名"
          />
        </a-form-item>

        <a-form-item
          label="登录邮箱"
          name="email"
          :rules="[{ required: true, message: '请输入登录邮箱!' }]"
        >
          <a-input
            v-model:value="formState.email"
            allow-clear
            style="width: 274px"
            placeholder="请输入学员登录邮箱"
          />
        </a-form-item>

        <a-form-item label="登录密码" name="password">
          <a-input-password
            v-model:value="formState.password"
            allow-clear
            style="width: 274px"
            placeholder="请输入登录密码"
          />
        </a-form-item>

        <a-form-item
          label="所属部门"
          name="dep_ids"
          :rules="[{ required: true, message: '请选择学员所属部门!' }]"
        >
          <a-tree-select
            v-model:value="formState.dep_ids"
            style="width: 274px"
            :tree-data="departments"
            tree-checkable
            allow-clear
            treeDefaultExpandAll
            placeholder="请选择学员所属部门"
          />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { Modal, message } from "ant-design-vue";
import UploadImageButton from "@/components/Common/upload-image-button.vue";
import memberDefaultAvatar from "@/assets/thumb/avatar.png";
import { user, department } from "@/api";

// 父组件传入的参数
interface Props {
  id: number;
  open: boolean;
  onCancel: () => void;
}
const props = defineProps<Props>();
const emit = defineEmits(["cancel"]);

// 状态
const visible = ref(false);
const init = ref(true);
const loading = ref(false);
const avatar = ref<string>(memberDefaultAvatar);
const departments = ref<any[]>([]);
const formRef = ref();
const formState = reactive<any>({
  name: "",
  email: "",
  password: "",
  avatar: "",
  dep_ids: [],
});

// 监听 open 和 id
watch(
  () => props.open,
  (val) => {
    visible.value = val;
    if (val && props.id !== 0) {
      init.value = true;
      getParams();
      getDetail();
      formState.password = "";
    }
  }
);

const getParams = () => {
  department.departmentList({}).then((res: any) => {
    const dep = res.data.departments;
    if (JSON.stringify(dep) !== "{}") {
      departments.value = checkArr(dep, 0);
    }
  });
};

const getDetail = () => {
  user.user(props.id).then((res: any) => {
    const u = res.data.user;
    Object.assign(formState, {
      email: u.email,
      name: u.name,
      avatar: u.avatar,
      idCard: u.id_card,
      dep_ids: res.data.dep_ids,
    });
    avatar.value =
      u.avatar === -1
        ? memberDefaultAvatar
        : res.data.resource_url[u.avatar];
    init.value = false;
  });
};

// 部门树处理
const checkArr = (departments: any[], id: number) => {
  const arr: any[] = [];
  for (let i = 0; i < departments[id].length; i++) {
    if (!departments[departments[id][i].id]) {
      arr.push({
        label: departments[id][i].name,
        value: departments[id][i].id,
      });
    } else {
      const newArr = checkArr(departments, departments[id][i].id);
      arr.push({
        label: departments[id][i].name,
        value: departments[id][i].id,
        children: newArr,
      });
    }
  }
  return arr;
};

const onAvatarSelected = (url: string, id: number) => {
  avatar.value = url;
  formState.avatar = id;
};

const onFinish = (values: any) => {
  if (loading.value) return;
  loading.value = true;
  user
    .updateUser(
      props.id,
      formState.email,
      formState.name,
      formState.avatar,
      formState.password || "",
      formState.idCard,
      formState.dep_ids
    )
    .then(() => {
      message.success("保存成功！");
      loading.value = false;
      handleCancel();
    })
    .catch(() => {
      loading.value = false;
    });
};

const onFinishFailed = (errorInfo: any) => {
  console.log("Failed:", errorInfo);
};

const handleOk = () => {
  (formRef.value as any)
    .validate()
    .then(() => {
      onFinish(formState);
    })
    .catch((error: any) => {
      console.log("验证失败", error);
    });
};

const handleCancel = () => {
  emit("cancel");
};
</script>

<style scoped>
.form-avatar {
  width: 64px;
  height: 64px;
  border-radius: 50%;
}
</style>
